package com.linux.huhx.server;

import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;

import java.util.concurrent.CountDownLatch;

/**
 * @Author: huhx
 * @Date: 2017-11-06 下午 5:18
 */
public class ZkNodeGetData {
    private static ZooKeeper zooKeeper;
    private static ZooKeeperConnection zooKeeperConnection;

    public static Stat ZkNodeExists(String path) throws KeeperException, InterruptedException {
        return zooKeeper.exists(path, true);
    }

    public static void main(String[] args) {
        String path = "/HuhxZkNode";
        final CountDownLatch connectedSignal = new CountDownLatch(1);

        try {
            zooKeeperConnection = new ZooKeeperConnection();
            zooKeeper = zooKeeperConnection.connect("localhost");
            Stat stat = ZkNodeExists(path);
            if (stat != null) {
                byte[] bytes = zooKeeper.getData(path, (Watcher) watchedEvent -> {
                    if (watchedEvent.getType() == Watcher.Event.EventType.None) {
                        switch (watchedEvent.getState()) {
                            case Expired:
                                connectedSignal.countDown();
                                break;
                        }
                    } else {
                        try {
                            byte[] bn = zooKeeper.getData(path, false, null);
                            String data = new String(bn, "UTF-8");
                            System.out.println(data);
                            connectedSignal.countDown();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    }
                }, null);
                String data = new String(bytes, "UTF-8");
                System.out.println(data);
                connectedSignal.await();
            } else {
                System.out.println("Node does not exists");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                zooKeeperConnection.close();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
